import $ from "jquery";
import style from "./index.module.less";
import { createMoviePage } from "../list";
import { getMovieList } from "../../api/movies";

let container;
const slideNum = 2;
function init() {
  container = $("<div>").addClass(style.pagecodecontainer).appendTo("#app");
}

init();

export function createPageCode(curPage, pageSize, pageTotal) {
  container.empty();
  pageTotal = Math.ceil(pageTotal / pageSize);

  function createPageItem(text, status, targetPage) {
    const pageItem = $("<span>").text(text).appendTo(container);
    const className = style[status];
    pageItem.addClass(className);

    if (Object.is(status, "")) {
      pageItem.on("click", async function () {
        const listdata = await getMovieList(targetPage, pageSize);
        createMoviePage(listdata.data.movieList);
        createPageCode(targetPage, pageSize, listdata.data.movieTotal);
      });
    }
  }

  //1 创建 首页
  if (curPage === 1) {
    createPageItem("首页", "disabled", 1);
  } else {
    createPageItem("首页", "", 1);
  }

  //2 创建 上一页
  if (curPage > 1) {
    createPageItem("上一页", "", curPage - 1);
  } else {
    createPageItem("上一页", "disabled", 1);
  }
  
  //3 创建  num
  let max = curPage + slideNum;
  let min = curPage - slideNum;
  if (max > pageTotal) {
    max = pageTotal;
    min = pageTotal - 2 * slideNum - 1;
  }
  if (min < 1) {
    min = 1;
    max = 2 * slideNum + 1;
  }

  for (let i = min; i <= max; i++) {
    if (i===curPage) {
        createPageItem("" + i, "checked", i);
    }else{
        createPageItem("" + i, "", i);
    }
   
  }

  //4 创建 下一页
  if (curPage < pageTotal) {
    createPageItem("下一页", "", curPage + 1);
  } else {
    createPageItem("下一页", "disabled", curPage);
  }

  //5 创建 尾页
  if (curPage === pageTotal) {
    createPageItem("尾页", "disabled", pageTotal);
  } else {
    createPageItem("尾页", "", pageTotal);
  }
}
